/**
 * @SetTypeHandler.java  COPYRIGHT xiaojian
 * 
 * Created on 2018年8月26日 下午1:52:38
 */
package xj.toolkit.db.mybatis;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.google.common.collect.Sets;

/**
 * @author <a href="mailto:cxj2000@gmail.com">xiaojian.cao</a>
 *
 */
public class SetTypeHandler extends BaseTypeHandler<Set<String>> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, Set<String> parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, StringUtils.join(parameter.iterator(), ","));
	}

	@Override
	public Set<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String value = rs.getString(columnName);
		if (value == null) {
			return Sets.newHashSet();
		}
		
		return Sets.newHashSet(StringUtils.split(value, ","));
	}

	@Override
	public Set<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String value = rs.getString(columnIndex);
		if (value == null) {
			return Sets.newHashSet();
		}
		
		return Sets.newHashSet(StringUtils.split(value, ","));
	}

	@Override
	public Set<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		String value = cs.getString(columnIndex);
		if (value == null) {
			return Sets.newHashSet();
		}
		
		return Sets.newHashSet(StringUtils.split(value, ","));
	}}

